import {Repository} from "typeorm";
import {ResultUtils} from "@/utils/resultUtils";
import {QueryFilter} from "@/typing/queryFilter";
import {ResultCode} from "@/conf/resultCodeConf";
import {Tx} from "@/modules/_/base/tx";
import {Inject} from "@nestjs/common";
import {REQUEST} from "@nestjs/core";


type TXCreate = { success: boolean; err: boolean; data: any; code: ResultCode; message: string; } | {
    success: boolean;
    err: boolean;
    data: any;
    code: ResultCode;
    message: any;
    errInfo: any;
}

export interface BaseServiceCriterion<T> {
    create(obj: T): Promise<TXCreate>

    remove(obj: T): Promise<TXCreate>

    update(id: number, obj: T): Promise<TXCreate>

    queryById(id: number): Promise<TXCreate>

    queryList(filter: QueryFilter): Promise<TXCreate>
}

export class BaseService<T = any> extends Tx implements BaseServiceCriterion<T> {

    constructor(repository: Repository<any>) {
        super(repository);
    }

    async create(obj: T) {
        return this.txExec(async (entityManager) => {
            const insertResult = await entityManager.insert(this.repository.target, obj);
            return insertResult.raw.insertId;
        })
    }

    async remove(obj: T) {
        return this.txExec(async (entityManager) => {
            return entityManager.remove(obj);
        })
    }

    async update(id: number, obj: T) {
        return this.txExec(async (entityManager) => {
            //@ts-ignore
            return entityManager.update<T>(this.repository.target, id, obj);
        });
    }

    async queryById(id: number) {
        try {
            const user = await this.repository.findOneBy({id});
            return ResultUtils.success(user);
        } catch (e) {
            return ResultUtils.error(null, "err", e);
        }
    }

    async queryList(filter: QueryFilter) {
        // 需要去映射 FilterEnum，排除异常的字段
        const user = await this.repository.find({where: {...filter}});
        if (user) {
            return ResultUtils.success(user);
        }
        return ResultUtils.error(null, "err", "");
    }

}
